import React from 'react';
import BaseComp from "../Base/BaseComp";
import {Button, Col, Drawer, Input, Pagination, Popconfirm, Row, Space, Spin, Tabs} from "antd";
import TableComp from "../TableComp";
import {findIndex, map, omit, filter, unionWith, isEmpty, indexOf, isFunction} from "lodash-es";
import QueryTable from "../QueryTable";
import PropTypes from "prop-types";
import styles from './index.module.less'
import {getContainerFunc} from "../Base/helper/lifeCycle";

const {TabPane} = Tabs;

/**
 * 批量操作-公用弹框
 */
export default class MultiActModal extends BaseComp {

    static propTypes = {
        ...BaseComp.propTypes,
        title: PropTypes.string,
        visible: PropTypes.bool,
        loading: PropTypes.bool,
        loadingComp: PropTypes.any,
        /**
         * 是否异步任务
         */
        isAsyn: PropTypes.bool,
        /**
         * QueryTable 的配置
         */
        qtConfig: PropTypes.object,
        /**
         * 执行选中数据-回调
         * @type {function(selectedRows:[{}])}
         */
        onActBySelected: PropTypes.func,
        /**
         * 执行满足条件数据-回调
         * @type {function(ajaxData:{})}
         */
        onActByFilter: PropTypes.func,
        /**
         * 需要用到的执行按钮。如果设置，则只有设置了的按钮可用。
         *  例如：actButtons = ['selected', 'filter']
         * @type {[string]}
         */
        actButtons: PropTypes.array,
        /**
         * 弹框组件(Drawer)的额外属性
         */
        modalProps: PropTypes.object,
        /**
         * 弹框的底部，额外的内容。
         * 比如：底部添加多一个按钮
         */
        moreFooter: PropTypes.any
    };

    /**
     * 右侧表格组件实例
     * @type { QueryTable | null}
     */
    tableIns = null;
    _selectedRows = [];

    get selectedRows() {
        return this._selectedRows;
    }

    set selectedRows(value) {
        this._selectedRows = value;

        if (this.selectedBtnIns) {
            let cnt = this._selectedRows ? this._selectedRows.length : 0;

            this.selectedBtnIns.forEach((ins) => {
                if (ins && ins.setCompProps) {
                    ins.setCompProps({cnt});
                }
            });
        }
    }

    /**
     * 已选中表格组件实例
     * @type { TableComp | null}
     */
    selectedTableIns = null;

    selectedBtnIns = [];

    /**
     * 是否“已经获取过列表数据”。
     *  true：获取过列表数据，才能操作“执行满足条件数据”
     * @type {boolean}
     */
    hadFetched = false;

    initState(props) {
        let superState = super.initState(props);
        return {
            ...superState,
            activeTabKey: 'list',
            actingSelected: false, // 是否正在“执行选中数据”
            actingFilter: false // 是否正在“执行满足条件数据”
        }
    }

    /**
     * 查看已选择的数据
     */
    hdlViewSelected() {
        if (this.selectedTableIns) {
            this.selectedTableIns.setSelectedKeys(map(this.selectedRows, (row) => (row.id)));
        }
        this.setState({activeTabKey: 'selected'});
    }

    /**
     * 当 QueryTable 选中的数据有变化时的回调
     * @param selectedRowKeys
     * @param selectedRows
     * @param moreProps
     */
    hdlChangeTable(selectedRowKeys, selectedRows, moreProps) {
        this.selectedRows = selectedRows;
        // console.log(`MultiActModal hdlChangeTable this.selectedRows:`, this.selectedRows);
    }

    /**
     * 当选中数据有变化时的回调(已选中的表格)
     * @param selectedRowKeys
     * @param selectedRows
     */
    hdlChangeTable2(selectedRowKeys, selectedRows) {
        // this.selectedBtnIns.setCompProps({cnt: selectedRows.length})
        this.selectedBtnIns.forEach((ins) => {
            if (ins && ins.setCompProps) {
                ins.setCompProps({cnt: selectedRows.length});
            }
        });
    }

    /**
     * 执行已选数据
     */
    hdlActBySelected() {
        const funcReturn = this.runPropsFunc('onActBySelected')(this.selectedRows);
        if (funcReturn instanceof Promise) {
            this.setState({actingSelected: true});
            return funcReturn.then(rsp => {
                if (this.getPropsByName('isAsyn') !== true) { // 不是异步任务，才继续执行
                    this.setState({actingSelected: false}, () => {
                        if (rsp && rsp.status === 200) {
                            this.afterActSuccess(rsp);
                        }
                    });
                }
                return rsp;
            });
        }
        return funcReturn;
    }

    /**
     * 执行满足条件数据
     */
    hdlActByFilter() {
        const funcReturn = this.runPropsFunc('onActByFilter')(this.tableIns.getAjaxData4List());
        if (funcReturn instanceof Promise) {
            this.setState({actingFilter: true});
            return funcReturn.then(rsp => {
                if (this.getPropsByName('isAsyn') !== true) {  // 不是异步任务，才继续执行
                    this.setState({actingFilter: false}, () => {
                        if (rsp && rsp.status === 200) {
                            this.afterActSuccess(rsp);
                        }
                    });
                }
                return rsp;
            });
        }
        return funcReturn;
    }

    /**
     * 执行成功之后的逻辑
     */
    afterActSuccess(rsp) {
        this.setState({actingFilter: false, actingSelected: false}, () => {
            // 清空“已选中数据”
            this.selectedRows = [];
            // 刷新“列表数据”
            this.tableIns.setSelectedKeys([], () => {
                this.tableIns && this.tableIns.fetchList();
            });
        });
    }

    /**
     * 打开高级搜索浮层
     */
    openSearch(isOpen = true, afterCb = null) {
        const {loading} = this.getProps();
        if (true !== loading && this.tableIns && this.tableIns.openSearch) {
            this.tableIns.openSearch({isOpen}, afterCb)
        }
    }

    /**
     * 已选列表 - 确定
     */
    hdlOk() {

        if ('list' !== this.state.activeTabKey) {
            // 在“已选列表”中点击“确认”
            this.selectedRows = this.selectedTableIns.getSelected();
            // console.log('this.selectedRows', this.selectedRows);
            this.tableIns.setSelectedKeys(map(this.selectedRows, (row) => (row.id)), () => {
                this.setState({activeTabKey: 'list'});
            });
        }
    }

    /**
     * 取消选择
     */
    hdlCancel() {
        if ('list' !== this.state.activeTabKey) {
            this.selectedBtnIns.forEach((ins) => {
                if (ins && ins.setCompProps) {
                    ins.setCompProps({cnt: this.selectedRows.length});
                }
            });
            this.setState({activeTabKey: 'list'});
        } else {
            this.runPropsFunc('onCancel')();
        }
    }

    mainRender(context) {
        const {title, visible, qtConfig = {}, appins, actButtons, customprops, loading, loadingComp, modalProps, moreFooter} = this.getProps();
        const loadingModal = loading;
        const {actingFilter, actingSelected} = this.state;
        const tableCols = qtConfig.colsConf || [];
        const searchProps = qtConfig.searchProps;
        // 如果当前弹框正在 loading，则不默认弹出高级过滤浮层
        if (searchProps && searchProps.defaultOpen && loading) {
            searchProps.defaultOpen = false;
        }
        let needSelectedBtn = true, needFilterBtn = true;
        if (!isEmpty(actButtons)) {
            if (indexOf(actButtons, 'selected') === -1) needSelectedBtn = false;
            if (indexOf(actButtons, 'filter') === -1) needFilterBtn = false;
        }
        let selectedStyle = {};
        let modalTl = title || '-';
        // 'crud.tip.confirm-action': '确认对选中的记录进行 [{name}] 操作吗？',
        let actSelectedConfirm = this.myFormatMessage('crud.tip.confirm-action', {name: modalTl});
        // 'crud.tip.confirm-tip': '确认进行 [{name}] 操作吗？',
        let actFilterConfirm = this.myFormatMessage('crud.tip.confirm-tip', {name: modalTl});

        const footerComp = (
            <Space>
                {
                    needSelectedBtn && (
                        <SelectedBtn
                            type="link"
                            onRef={(ref) => {
                                this.selectedBtnIns.push(ref);
                            }}
                            disabled={'list' !== this.state.activeTabKey || actingFilter || loadingModal}
                            cnt={this.selectedRows.length}
                            style={selectedStyle}
                            onClick={this.hdlViewSelected.bind(this)}
                        />
                    )
                }
                {
                    'list' === this.state.activeTabKey ? (
                        <>
                            {
                                isFunction(moreFooter) ? moreFooter(this): (moreFooter || null)
                            }
                            {
                                needSelectedBtn && (
                                    <Popconfirm
                                        title={actSelectedConfirm}
                                        onConfirm={this.hdlActBySelected.bind(this)}
                                        disabled={actingFilter || loadingModal}
                                    >
                                        <SelectedBtn type={'primary'}
                                                     ghost={true}
                                                     onRef={(ref) => {
                                                         this.selectedBtnIns.push(ref);
                                                     }}
                                                     loading={actingSelected}
                                                     disabled={actingFilter || loadingModal}
                                                     cnt={this.selectedRows.length}>
                                            {this.formatMsgByCn('执行选中数据')}
                                        </SelectedBtn>
                                    </Popconfirm>
                                )
                            }
                            {
                                needFilterBtn && (
                                    <Popconfirm
                                        title={actFilterConfirm}
                                        onConfirm={this.hdlActByFilter.bind(this)}
                                        disabled={actingSelected || loadingModal || !this.hadFetched}
                                    >
                                        <Button type={'primary'}
                                                ghost={true}
                                                loading={actingFilter}
                                                disabled={actingSelected || loadingModal || !this.hadFetched}>
                                            {this.formatMsgByCn('执行满足条件数据')}
                                        </Button>
                                    </Popconfirm>
                                )
                            }
                        </>
                    ) : (
                        <Button type="primary"
                                disabled={actingFilter || actingSelected || loadingModal}
                                onClick={this.hdlOk.bind(this)}
                        >
                            {this.formatMsgByCn('确定')}
                        </Button>
                    )
                }
                <Button disabled={actingFilter || actingSelected || loadingModal}
                        onClick={this.hdlCancel.bind(this)}>
                    {this.formatMsgByCn('取消')}
                </Button>
            </Space>
        );

        return (
            <Drawer
                title={modalTl}
                visible={visible}
                onClose={this.hdlCancel.bind(this)}
                width={900}
                bodyStyle={{padding: '0 8px', height: '100%'}}
                footer={footerComp}
                // footerStyle={{textAlign: "center"}}
                keyboard={false}
                // closable={true}
                // maskClosable={!(actingFilter || actingSelected)}
                getContainer={() => getContainerFunc(this)}
                {...(modalProps || {})}
            >
                <Tabs activeKey={this.state.activeTabKey}
                      tabBarStyle={{display: 'none'}}
                      className={styles.contain}>
                    <TabPane tab="list" key="list" style={{height: '100%'}}>
                        <QueryTable
                            {...omit(qtConfig, ['rowSelect'])}
                            style={{height: '100%'}}
                            appins={appins}
                            customprops={customprops}
                            isTpl={false}
                            selecting={needSelectedBtn}
                            rowSelect={needSelectedBtn}
                            rowSelection={{
                                onChange: this.hdlChangeTable.bind(this),
                            }}
                            onRef={(ref) => {
                                this.tableIns = ref;
                                ref.setSelectedKeys(map(this.selectedRows, (row) => (row.id)));
                            }}
                            afterFetchList={(rsp) => {
                                // 获取列表数据之后
                                if (!this.hadFetched) {
                                    this.hadFetched = true;
                                    this.reRender();
                                }
                            }}
                        />
                    </TabPane>
                    <TabPane tab="selected" key="selected" style={{height: '100%'}}>
                        <div style={{paddingTop: 8, height: '100%'}}>
                            <TableComp
                                style={{height: '100%'}}
                                selecting={true}
                                rowSelect={true}
                                rowSelection={{
                                    onChange: this.hdlChangeTable2.bind(this),
                                }}
                                multi={true}
                                needNO={true}
                                onRef={(ref) => {
                                    this.selectedTableIns = ref;
                                    ref.setSelectedKeys(map(this.selectedRows, (row) => (row.id)));
                                }}
                                colsConf={tableCols}
                                dataSource={[...this.selectedRows]}
                                pagination={{
                                    pageSize: 40,
                                    position: ['bottomCenter'],
                                    size: "small",
                                    // simple: true,
                                    style: {margin: '5px 0'}
                                }}
                            />
                        </div>
                    </TabPane>
                </Tabs>

                {
                    loading && (
                        <Spin className={styles.loading} indicator={loadingComp}/>
                    )
                }
            </Drawer>
        )
    }
}

class SelectedBtn extends BaseComp {

    mainRender() {
        const {cnt = 0, txt, onRef, children, disabled, ...restProps} = this.getProps();
        return (
            <Button {...restProps}
                    disabled={!(cnt > 0) || disabled}
            >
                {
                    !isEmpty(children) ? children : (
                        `${this.formatMsgByCn(txt || '已选择')} (${cnt})`
                    )
                }
            </Button>
        )
    }
}